import React from 'react';
import { connect } from 'dva'
import moment from 'moment'

import Tools from 'utils/tools';

import styles from './style/indicators.less'
import Title from 'components/Title'
import Iconfont from 'components/Iconfont';

import { config } from 'utils';
const { scada } = config;
const {
  Token,
  DdToken,
  Interval,
  IntervalMonth,
  StationIds,
  STypes,
  DTypes,
} = scada;
const format = 'YYYY-MM-DD';

@connect(({ business }) => ({ ...business }))
class Indicators extends React.Component {
  static defaultProps = {
    abstractList: [
      {
        label: '供水量', key: 'waterSupply', unit: 'm³', icon: 'output',
        dataResource: 'SupplyWaterResourceUnique_supply_Indicators',
        server: {
          type: 'business/querySupplyWater', payload: { type: 'Unique_supply_Indicators', StationId: StationIds.supply.join(',') }
        },
      },
      {
        label: '售水量', key: 'waterSell', unit: 'm³', icon: 'yield',
        dataResource: 'SellWaterResourceUnique_sell_Indicators',
        server: {
          type: 'business/querySellWater', payload: { type: 'Unique_sell_Indicators' }
        },
      },
      {
        label: '产销差', key: 'waterSubtract', unit: 'm³', icon: 'line',
      },
      {
        label: '实收金额', key: 'SumPay', unit: '元', icon: 'pay',
        dataResource: 'IncomingResourceUnique_Pay_Indicators',
        server: {
          type: 'business/queryIncomingModel', payload: { type: 'Unique_Pay_Indicators', ids: "" }
        }
      },
      {
        label: '抄表块数', key: 'DivisionCopy', unit: '个', icon: 'flowmeter',
        dataResource: 'DivisionCopyrateResourceUnique_DivisionCopy_Indicators',
        server: {
          type: 'business/queryDivisionCopyrate', payload: { type: 'Unique_DivisionCopy_Indicators' }
        },
      },
      {
        label: '抄见率', key: 'DivisionCopyRadio', unit: '%', icon: 'order_edit',
        dataResource: 'DivisionCopyrateResourceUnique_DivisionCopy_Indicators',
      },
    ],
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    await this.setDateIndicators()
  }

  // 获取指标
  setDateIndicators = async () => {
    const { abstractList } = this.props;
    abstractList.map(ele => {
      const { server } = ele;
      if (server) this.queryServer(server);
    })
  }

  queryServer = async (server) => {
    // ['2019-10', '2019-09','2018-10']
    const CurrentMonth = moment(); // 本月(2019-10-01)
    const LastMonth = moment().add(-1, 'months'); // 上月(2019-09-01)
    const LastYearMonth = moment().add(-1, 'years'); // 去年同月（2018-10-01）
    const timeArr = [
      { value: CurrentMonth, label: 'CurrentMonth' },
      { value: LastMonth, label: 'LastMonth' },
      { value: LastYearMonth, label: 'LastYearMonth' }
    ]
    // 供水量
    let { payload, type } = server;
    const { type: unType } = payload;

    let payloads = {};
    let servers = {};

    // 供水量
    if(type === 'business/querySupplyWater'){
      timeArr.map(ele =>{
        const { value, label } = ele;
        Object.assign(payloads, payload,{
          Token,
          Interval,
          STypes,
          DTypes,
          Begin: moment(value).startOf('month').unix(),
          End: moment(value).unix(),
          type: `${unType}${label}`
        })
        Object.assign(servers, server, { payload: payloads })
        this.props.dispatch(servers);
      });
    }else if(type === 'business/queryDivisionCopyrate'){
      timeArr.map(ele =>{
        const { value, label } = ele;
        Object.assign(payloads, payload,{
          Token: DdToken,
          interval: IntervalMonth,
          begin: moment(value).startOf('month').unix(),
          end: moment(value).unix(),
          type: `${unType}${label}`
        })
        Object.assign(servers, server, { payload: payloads })
        this.props.dispatch(servers);
      });
    }else {
      // 售水、已收消费 条件相同
      timeArr.map(ele =>{
        const { value, label } = ele;
        // 售水量
        Object.assign(payloads, payload, {
          startDate: moment(value).startOf('month').format(format),
          endDate: moment(value).format(format),
          type: `${unType}${label}`
        })
        Object.assign(servers, server, { payload: payloads })
        this.props.dispatch(servers);
      })
    }
  }

  getData = (params, timeArr = ['CurrentMonth', 'LastMonth', 'LastYearMonth']) => {
    const { props } = this;
    let result = {};
    let valueCount = 0; // 本月
    let yearRadio = 0;  // 同比（201910-201810）/ 201810
    let monthRadio = 0; // 环比（201910-201909）/201909
    let monthValue = 0;     // 去年同月(201910 - 201810)
    let lastMonthValue = 0; // 上月(201910 - 201909)

    const { key, dataResource, server, other } = params;
    // 处理数据：去年同月（2018-10）、上月（2019-09）、本月（2019-10）
    if(key === 'waterSupply'){ // 供水
      valueCount = Tools.countSupplyWater(props[`${dataResource}${timeArr[0]}`])
      const LastMonthCount =  Tools.countSupplyWater(props[`${dataResource}${timeArr[1]}`])
      const LastYearMonthCount = Tools.countSupplyWater(props[`${dataResource}${timeArr[2]}`])
      
      monthValue = valueCount - LastYearMonthCount
      lastMonthValue = valueCount - LastMonthCount
      yearRadio = LastYearMonthCount === 0 ? 0 : (monthValue/LastYearMonthCount).toFixed(2) * 1
      monthRadio = LastMonthCount === 0 ? 0 :(lastMonthValue/LastMonthCount).toFixed(2) * 1
    }else if(key === 'waterSell') { // 售水
      valueCount = Tools.countSellWater(props[`${dataResource}${timeArr[0]}`])
      const LastMonthCount =  Tools.countSellWater(props[`${dataResource}${timeArr[1]}`])
      const LastYearMonthCount = Tools.countSellWater(props[`${dataResource}${timeArr[2]}`])
      
      monthValue = valueCount - LastYearMonthCount
      lastMonthValue = valueCount - LastMonthCount
      yearRadio = LastYearMonthCount === 0 ? 0 : (monthValue/LastYearMonthCount).toFixed(2) * 1
      monthRadio = LastMonthCount === 0 ? 0 :(lastMonthValue/LastMonthCount).toFixed(2) * 1
    }else if(key === 'waterSubtract'){ // 差销差（供水 -  售水）
      valueCount = Tools.countSupplyWater(props[`SupplyWaterResourceUnique_supply_Indicators${timeArr[0]}`]) - Tools.countSellWater(props[`SellWaterResourceUnique_sell_Indicators${timeArr[0]}`]);
      const LastMonthCount =  Tools.countSupplyWater(props[`SupplyWaterResourceUnique_supply_Indicators${timeArr[1]}`]) - Tools.countSellWater(props[`SellWaterResourceUnique_sell_Indicators${timeArr[1]}`]);
      const LastYearMonthCount = Tools.countSupplyWater(props[`SupplyWaterResourceUnique_supply_Indicators${timeArr[2]}`]) - Tools.countSellWater(props[`SellWaterResourceUnique_sell_Indicators${timeArr[2]}`]);

      monthValue = valueCount - LastYearMonthCount
      lastMonthValue = valueCount - LastMonthCount
      yearRadio = LastYearMonthCount === 0 ? 0 : (monthValue/LastYearMonthCount).toFixed(2) * 1
      monthRadio = LastMonthCount === 0 ? 0 :(lastMonthValue/LastMonthCount).toFixed(2) * 1
    }else if(key === 'SumPay'){
      valueCount = Tools.countSumPay(props[`${dataResource}${timeArr[0]}`])
      const LastMonthCount =  Tools.countSumPay(props[`${dataResource}${timeArr[1]}`])
      const LastYearMonthCount = Tools.countSumPay(props[`${dataResource}${timeArr[2]}`])
      // Fix: 精度丢失
      monthValue = (valueCount *1000 - LastYearMonthCount *1000)/1000
      lastMonthValue = (valueCount *1000 - LastMonthCount *1000)/1000
      yearRadio = LastYearMonthCount === 0 ? 0 : (monthValue/LastYearMonthCount).toFixed(2) * 1
      monthRadio = LastMonthCount === 0 ? 0 :(lastMonthValue/LastMonthCount).toFixed(2) * 1
    }else if(key === 'DivisionCopy'){
      valueCount = props[`${dataResource}${timeArr[0]}`] && (props[`${dataResource}${timeArr[0]}`].succ || props[`${dataResource}${timeArr[0]}`].succ === 0) ? props[`${dataResource}${timeArr[0]}`].succ: 0;
      const LastMonthCount =  props[`${dataResource}${timeArr[1]}`] && (props[`${dataResource}${timeArr[1]}`].succ || props[`${dataResource}${timeArr[1]}`].succ === 0) ? props[`${dataResource}${timeArr[1]}`].succ: 0;
      const LastYearMonthCount = props[`${dataResource}${timeArr[2]}`] && (props[`${dataResource}${timeArr[2]}`].succ || props[`${dataResource}${timeArr[2]}`].succ === 0) ? props[`${dataResource}${timeArr[2]}`].succ: 0;

      monthValue = valueCount - LastYearMonthCount
      lastMonthValue = valueCount - LastMonthCount
      yearRadio = LastYearMonthCount === 0 ? 0 : (monthValue/LastYearMonthCount).toFixed(2) * 1
      monthRadio = LastMonthCount === 0 ? 0 :(lastMonthValue/LastMonthCount).toFixed(2) * 1
    }else if(key === 'DivisionCopyRadio'){
      valueCount = props[`${dataResource}${timeArr[0]}`] && (props[`${dataResource}${timeArr[0]}`].copyRate || props[`${dataResource}${timeArr[0]}`].copyRate === 0) ? props[`${dataResource}${timeArr[0]}`].copyRate: 0;
      const LastMonthCount =  props[`${dataResource}${timeArr[1]}`] && (props[`${dataResource}${timeArr[1]}`].copyRate || props[`${dataResource}${timeArr[1]}`].copyRate === 0) ? props[`${dataResource}${timeArr[1]}`].copyRate: 0;
      const LastYearMonthCount = props[`${dataResource}${timeArr[2]}`] && (props[`${dataResource}${timeArr[2]}`].copyRate || props[`${dataResource}${timeArr[2]}`].copyRate === 0) ? props[`${dataResource}${timeArr[2]}`].copyRate: 0;
      // Fix: 精度丢失
      monthValue = (valueCount * 1000 - LastYearMonthCount * 1000)/1000
      lastMonthValue = (valueCount * 1000 - LastMonthCount * 1000)/1000
      yearRadio = LastYearMonthCount === 0 ? 0 : (monthValue/LastYearMonthCount).toFixed(3) * 1
      monthRadio = LastMonthCount === 0 ? 0 :(lastMonthValue/LastMonthCount).toFixed(3) * 1
    }
    result = { value: valueCount, yearRadio, monthRadio, monthValue, lastMonthValue}
    return result;
  }

  // 指标渲染
  RenderIndicators = () => {
    const { props } = this;
    const { abstractList } = props;

    return (<div className={`${styles.Comm} clearfix`}>
      {
        abstractList.map((ele, index) => {
          const { unit, icon, label, dataResource, other } = ele;
          // const { zoom = 1 } = other;
          
          const Resource = this.getData(ele);
          return (
            <div key={index} className={`${styles.items} ${styles.isColorful} ${styles['col-12']}`}>
              <div className={styles.header}>
                <div className={styles.icon}><Iconfont type={icon} /></div>
                <span>{label}（{unit}）</span>
              </div>
              <div className={styles.inner}>
                <div className={styles.num}>
                  {Tools.formatEmpty(Resource, 'value')}{unit === '%' ? unit : ''}
                </div>
                {this.renderInner(Resource)}
              </div>
            </div>)
        })
      }
    </div>)
  }

  renderValue(data, key) {
    let dom = '-'
    if (data && (data[key] || data[key] === 0)) {
      const value = data[key];
      let flag = (value === 0 || value > 0) ? true : false;
      let clsName = flag ? styles.success : styles.error;
      let val = flag ? value : value * -1;
      let icon = flag ? 'arrow-up' : 'arrow-down'
      dom = (<span className={clsName}><Iconfont type={icon} />{val}</span>)
    }
    return (<>{dom}</>);
  }

  // 水质检测
  renderInner(data) {
    return (<div className={styles.list}>
      同比{Tools.formatEmpty(data, 'yearRadio')}% &nbsp;
      环比{Tools.formatEmpty(data, 'monthRadio')}%
      <br />
      <label>同月{this.renderValue(data, 'monthValue')}</label>
      <label>上月{this.renderValue(data, 'lastMonthValue')}</label>
    </div>)
  }

  render() {
    return (
      <Title title={'重点指标监控'} style={{ 'padding': '2%' }}>
        {this.RenderIndicators()}
      </Title>
    )
  }
}

export default Indicators;
